<template>
	<el-form @keyup.enter="login" ref="loginForm"  :model="form" :rules="rules" label-width="0" size="large">
		<el-form-item prop="user">
			<el-input v-model="form.user" prefix-icon="el-icon-user" clearable :placeholder="$t('login.userPlaceholder')">
				<!-- <template #append>
					<el-select v-model="userType" style="width: 130px">
						<el-option :label="$t('login.admin')" value="admin"></el-option>
						<el-option :label="$t('login.user')" value="user"></el-option>
					</el-select>
				</template> -->
			</el-input>
		</el-form-item>
		<el-form-item prop="password">
			<el-input
				v-model="form.password"
				prefix-icon="el-icon-lock"
				clearable
				show-password
				:placeholder="$t('login.PWPlaceholder')"
			></el-input>
		</el-form-item>
		<el-form-item prop="code">
			<div style="width:400px;height:40px; display: flex;justify-content: space-between;">
				<el-input
					v-model="form.code"
					prefix-icon="sc-icon-code"
					clearable
					style="width:800px"
					:placeholder="$t('login.CodePlaceholeder')"
				></el-input>
				<!-- <el-image :src="codeUrl" placeholder="" fit="cover" /> -->
				<img style="width:100%;height: 100%;margin-left:20px;"  :src="codeUrl" @click="generateCode()" />
				<!-- <el-button type="primary" style="width: 100%;height: 100%;margin-left:20px;" v-else :loading="loading"  @click="generateCode()">获取验证码</el-button> -->
			</div>
		</el-form-item>
		<el-form-item style="margin-bottom: 10px">
			<!-- <el-col :span="12">
				<el-checkbox v-model="form.autologin" :label="$t('login.rememberMe')"></el-checkbox>
			</el-col> -->
			<!-- <el-col :span="12" class="login-forgot">
				<router-link to="/reset_password">{{ $t('login.forgetPassword') }}？</router-link>
			</el-col> -->
		</el-form-item>
		<el-form-item>
			<el-button type="primary" style="width: 100%" :loading="islogin" round @click="login">{{
					$t('login.signIn')
				}}</el-button>
		</el-form-item>
		<!-- <div class="login-reg">
			{{ $t('login.noAccount') }} <router-link to="/user_register">{{ $t('login.createAccount') }}</router-link>
		</div> -->
	</el-form>
</template>

<script>
import jwt_decode from 'jwt-decode'
import { v4 as uuidv4 } from 'uuid'
import JSEncrypt from 'jsencrypt'
export default {
	data() {
		return {
			userType: 'admin',
			form: {
				// user: import.meta.env.VITE_NODE_ENV === 'dev' ? '15823344805' : '',
				// password: import.meta.env.VITE_NODE_ENV === 'dev' ? '7d869msY' : '',
				user: import.meta.env.VITE_NODE_ENV === 'dev' ? '15823344805' : '',
				password: import.meta.env.VITE_NODE_ENV === 'dev' ? '7d869msy' : '',
				code: '',
				autologin: false
			},
			rules: {
				user: [{ required: true, message: this.$t('login.userError'), trigger: 'blur' }],
				password: [{ required: true, message: this.$t('login.PWError'), trigger: 'blur' }],
				code: [{ required: true, message: this.$t('login.CodeError'), trigger: 'blur' }]
			},
			islogin: false,
			codeId: '',
			codeUrl: '',
			loading:false
		}
	},
	watch: {
		userType(val) {
			if (val === 'admin') {
				this.form.user = 'admin'
				this.form.password = 'admin'
			} else if (val === 'user') {
				this.form.user = 'user'
				this.form.password = 'user'
			}
		}
	},
	mounted() {
		this.generateCode()
	},
	methods: {
		async generateCode() {
			// 生成唯一标识符
			const timestamp = Date.now()
			this.codeId = `${uuidv4()}-${timestamp}`
			console.log('进入生成方法' + this.codeId)
			// 调用接口获取验证码图片
			// this.loading = true
			await this.$API.basic.generateCode
				.post({ data: { codeId: this.codeId } })
				.then((response) => {
					// this.loading = false
					console.log(response)
					// 将响应中的图像数据作为base64编码字符串返回
					const imageBase64 = btoa(
						new Uint8Array(response).reduce((data, byte) => data + String.fromCharCode(byte), '')
					)
					// 使用base64编码字符串来显示图像
					this.codeUrl = `data:image/jpeg;base64,${imageBase64}`
				})
				.catch((err) => {
					console.log(err)
					// this.loading = false
				})
			// 将返回的字节数组转换为字符串
			// const decoder = new TextDecoder('utf-8')
			// const resultStr = decoder.decode(new Uint8Array(response))
			// 将结果字符串解析为 Base64 图像数据
			// const base64Image = resultStr.replace(/^data:image\/(png|jpeg|jpg);base64,/, '')

			// 设置图像 URL
			// this.codeUrl = `data:image/jpeg;base64,${base64Image}`
			console.log(this.codeUrl)
		},
		async login() {
			var validate = await this.$refs.loginForm.validate().catch(() => {})
			if (!validate) {
				return false
			}

			this.islogin = true
			// 设置秘钥
			const secretKey = 'Key1SecRETnc12Co'
			// 加密配置
			var easConfig = { mode: 'ECB', padding: 'Pkcs7' }

			//ssl生成的公钥
			const pubKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJIMt6SCsx+KiBuagZmEtYBo+OnMJBCgKLWsJ1dw7k6bzzRWmDA2AQFxNo2xYkMrDkKOQpNXbUyrw1/mxKI3amsCAwEAAQ=='
			const encryptor = new JSEncrypt()  // 创建加密对象实例
			encryptor.setPublicKey(pubKey)//设置公钥
			let rsaAccount = encryptor.encrypt(this.form.user)  //对账号进行加密
			let rsaPassWord = encryptor.encrypt(this.form.password)  //对密码进行加密

			var data = {
				// account: this.form.user,
				// password: this.form.password,
				// account: this.$TOOL.crypto.AES.encrypt(this.form.user, secretKey, easConfig),
				// password: this.$TOOL.crypto.AES.encrypt(this.form.password, secretKey, easConfig),
				account: rsaAccount,
				password: rsaPassWord,
				// codeId: this.$TOOL.crypto.AES.encrypt(this.codeId, secretKey, { mode: 'CBC', padding: 'Pkcs7' }),
				codeId: this.codeId,
				code: this.form.code
				//	password: this.$TOOL.crypto.MD5(this.form.password)
			}
			//获取token
			var user = await this.$API.basic.token.post({ data: data })
			this.islogin = false

			if (user.code == 0) {
				this.$TOOL.cookie.set('TOKEN', user.data, {
					expires: this.form.autologin ? 24 * 60 * 60 : 0
				})
				// console.log(user.data)
				// this.$TOOL.data.set('USER_INFO', user.data.userInfo)
				const decodeToken = jwt_decode(user.data).userName
				this.$TOOL.data.set('USER_INFO', { userName: decodeToken })
				let menu = await this.$API.basic.home.menu.get()
				// let permissions = await this.$API.basic.power.permissions.post({})
				// let
				let defaultUrl = ''
				if (menu.code == 0) {
					if (menu.data.menu.length === 0) {
						this.islogin = false
						this.$alert('当前用户无任何菜单权限，请联系系统管理员', '无权限访问', {
							type: 'error',
							center: true
						})
						return false
					}

					// if(permissions.code == 0){
					this.$TOOL.data.set('PERMISSIONS', menu.data.permissions)
					// }
					this.$TOOL.data.set('MENU', menu.data.menu)
					defaultUrl = menu.data.url

					// menu.data.permissions = [ 'activity-direct-totality','activity-direct-product',
					// 'activity-overview-direct-area','activity-overview-direct-client','activity-KA-totality','activity-overview-KA-product',
					// 'activity-overview-KA-area','activity-overview-KA-client',
					// ]
				} else {
					this.islogin = false
					this.$message.warning(menu.message)
					return false
				}

				if(!defaultUrl){
					this.$router.replace({
						path: '/'
					})
				}else{
					this.$router.replace({
						path: defaultUrl
					})
				}

				this.$message.success('Login Success 登录成功')
			}
		}
	}
}
</script>
<style></style>
